﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Singer.Core;
using Singer.Middleware.JwtAuth;
using Singer.Shared;
using Singer.Shared.UserContext;
using Singer.UnitTestWeb.Domain.Users;
using System.Security.Claims;

namespace Singer.UnitTestWeb.Controllers
{
    public class JwtAuthController : ApiControllerBase
    {
        IJwtAuthTokenManager _jwtAuthTokenManager;
        IFreeSql _freeSql;
        public JwtAuthController(IJwtAuthTokenManager jwtAuthTokenManager, IFreeSql freeSql, IServiceProvider serviceProvider) : base(serviceProvider)
        {
            _jwtAuthTokenManager = jwtAuthTokenManager;
            _freeSql = freeSql;
        }

        [AllowAnonymous]
        [HttpGet]
        public async Task<string> LoginAsync(string mobile, string pwd)
        {
            var user = await _freeSql.Select<User>().Where(x => x.Account == mobile && x.Password == pwd).FirstAsync();
            if (user == null)
                throw new CoreException("用户名或密码错误");
            // 有效载荷 保存登录的用户信息
            var claims = new Claim[]
            {
                new Claim(nameof(IUserContext.UserId), user.Id.ToString()),
                new Claim(nameof(IUserContext.UserName), user.Name??""),
                new Claim(nameof(IUserContext.Mobile), user.Mobile??""),
                new Claim(nameof(user.Account), user.Account ?? "")
            };
            string token = await _jwtAuthTokenManager.CreateTokenAsync(claims);
            return token;
        }

        [HttpGet]
        public string GetData(string msg)
        {
            if (UserContext == null)
                throw new CoreException("找不到当前登录的用户信息");
            string info = "当前登录的用户信息：" + JsonUtils.ToJson(UserContext) + "/r/n 传入的msg：" + msg;
            return info;
        }
    }
}
